import { ref } from 'vue'
import type { RandomTestingStore } from '.'
import { edit, view } from '@/apis/InterviewQuestions'
import type { InterviewQuestionsEdit } from '@/models/InterviewQuestions/InterviewQuestionsEdit'
import { message, notification } from 'ant-design-vue'
import type InterviewQuestionsForm from '@/pages/IssueStorage/InterviewQuestionsForm.vue'

const entityName = '题目'

export class InterviewQuestionsEditFormStore {
  constructor(rootStore: RandomTestingStore) {
    this.rootStore = rootStore
  }

  rootStore

  /**
   * 是否展示Modal
   */
  modal = ref(false)

  /**
   * 表单Loading
   */
  loading = ref(false)

  /**
   * 表单实例
   */
  formRef = ref<null | InstanceType<typeof InterviewQuestionsForm>>()

  onClickEdit = () => {
    const { rootStore } = this
    const { renderQuestionStore } = rootStore
    const { id } = renderQuestionStore
    if (!id) return
    this.onEdit(id.value)
  }

  onEdit = async (id?: number) => {
    const { rootStore } = this
    const { interviewQuestionsEditFormDataStore } = rootStore
    if (!id) return
    this.modal.value = true
    this.loading.value = true
    try {
      const res = await view(id)
      if (res.data) {
        interviewQuestionsEditFormDataStore.setFormState({
          ...res.data,
          id,
        })
        this.formRef.value?.setFormStata({ ...interviewQuestionsEditFormDataStore.formState })
      }
    } catch (error) {}
    this.loading.value = false
  }

  onCancel = () => {
    const { rootStore } = this
    const { interviewQuestionsEditFormDataStore } = rootStore
    interviewQuestionsEditFormDataStore.resetFormState()
    this.formRef.value?.resetFormStata()
    this.modal.value = false
  }

  onOk = async () => {
    const { rootStore } = this
    const { interviewQuestionsEditFormDataStore, randomTestStore } = rootStore
    const formData = await this.formRef.value?.getFormState()
    if (this.loading.value) return
    if (!formData) return
    interviewQuestionsEditFormDataStore.setFormState({
      ...formData,
      id: interviewQuestionsEditFormDataStore.formState.id,
    })
    if (!interviewQuestionsEditFormDataStore.formState.id) return
    this.loading.value = true
    try {
      const res = await edit({
        ...interviewQuestionsEditFormDataStore.formState,
      } as InterviewQuestionsEdit)
      if (res.data) {
        message.success(`修改${entityName}成功!`)
        this.loading.value = false
        randomTestStore.init()
        this.onCancel()
        return
      } else {
        notification.error({ message: `修改${entityName}失败!` })
      }
    } catch (error) {
      notification.error({
        message: `修改${entityName}失败!`,
      })
    }
    this.loading.value = false
    this.onCancel()
  }
}
